##################################################################
# File : /lua/ui/controls/cryptedit.lua
# Description : Crypted edit control
# Author : Neruz
##################################################################

local Edit = import('/lua/maui/edit.lua').Edit


CryptEdit = Class(Edit) {
	__init = function(self, parent, debugname)
		Edit.__init(self, parent, debugname)
		self.cryptedText = {}
		self.crypted = true
		self.origOnCharPressed = Edit.OnCharPressed
		self.origOnTextChanged = Edit.OnTextChanged
	end,
	
    GetCryptedText = function(self)
    	local text = (''):join(self.cryptedText)
    	return text
    end,
    
    SetCryptedText = function(self, text)
    	self.cryptedText = {}
    	local textLen = text:len()
    	local displayedText = ''
    	for c = 1, textLen do
    		local char = string.sub(text, c, c + 1)
    		table.insert(self.cryptedText, char) 
    		displayedText = displayedText .. '*'
    	end
    	self:SetText(displayedText)
    end,
    
    SetCrypted = function(self, bool)
    	if bool then
    		local text = self:GetText()
    		self:SetCryptedText(text)
    	else
    		local text = self:GetCryptedText()
    		self:SetText(text)
    		self.cryptedText = {}
    	end
    	self.crypted = bool
    end,
    
    OnCharPressed = function(self, charcode)
    	local caretPos = self:GetCaretPosition()
		local char = string.char(charcode)
		table.insert(self.cryptedText, caretPos + 1, char)
		self:SetText(self:GetText() .. '*')
		self:SetCaretPosition(caretPos + 1)
    	#LOG(self:GetText(), repr(self.textCache))
		return true
    end,
    
    OnTextChanged = function(self, newText, oldText)
    	local newLen = newText:len()
    	local oldLen = oldText:len()
    	if newLen < oldLen then
    		local caretPos = self:GetCaretPosition()
    		table.remove(self.cryptedText, caretPos + 1)
    		#LOG(self:GetText(), repr(self.textCache))
    	end
    	if newLen == 0 then
    		self:SetCryptedText('')
    	end
    end,
}